<!--备件订单制作-->
<template>
  <div>
    <el-dialog
      ref="isPopWindows"
      v-dialogDrag
      :title="textMap[popupsState]"
      :visible.sync="isViewPopWindows"
      width="85%"
      :append-to-body="true"
      :close-on-click-modal="false"
      center
      @close="close"
      @open="open"
    >
      <dialogHeader
        slot="title"
        :title="textMap[popupsState]"
        :style-type="$store.state.app.dialogType"
      />
      <div class="formBoxContain">
        <one-table-template
          ref="multipleTable"
          :refresh-table-key="tableKey"
          :dynamic-buttons="tableButtons"
          :dynamic-components="tableComponents"
          :dynamic-api-config="{}"
          :dynamic-table-cols="tableCols"
          :dynamic-form-fields="formField"
          :text-messages="{
            text:'订货种类：' + totalType + '(种)  订货总金额：' + (formField.purOrderType === 'A002' ? totalPurUrgentOrderPriceAmount : totalAmount) + '(元)'
          }"
          :dynamic-table-defult-height="350"
          :dynamic-is-show-select="true"
          :dynamic-is-init-table="false"
          :dynamic-is-show-more-btn="true"
          :dynamic-is-fix-index="false"
          :is-show-pagination="false"
          :callback-obj="callbackObj"
        >
          <template #isCanLack="scope">
            <el-checkbox
              v-model="scope.row.isCanLack"
              true-label="1"
              false-label="0"
            />
          </template>
          <template #urgentOrderPrice="scope">
            <span>{{Number(scope.row.urgentOrderPrice) == 0 ? scope.row.purPrice : scope.row.urgentOrderPrice }}</span>
          </template>
          <template #purQty="scope">
            <el-input
              :key="scope.col.prop"
              v-model="scope.row.purQty"
              placeholder="请输入数量"
              clearable
              @change="numChange($event, scope.row, scope.col, scope.$index)"
            />
          </template>
        </one-table-template>
      </div>
    </el-dialog>
    <!-- 缺件导入 -->
    <short-import
      :is-view-short-windows="isViewShortWindows"
      @close="closeShort"
      @selectiondata="selectiondata1"
      :short-list="shortList"
    />
    <!-- 售后技术需求导入 -->
    <!-- <after-sale-import
      :is-after-sale-import="isAfterSaleImport"
      @addData="addData"
      @close="closeSale"
      :short-list="shortList"
    /> -->
    <part-select
      ref="isAfterSaleImport"
      :is-view-part.sync="isAfterSaleImport"
      :row-data="rowData"
      :custom="customObj"     
      :chosen-list.sync="chosenList"
      :cur-select-list.sync="curSelectList"
      @selectiondataPart="selectiondata2"
      :short-list="shortList"
    />

    <!-- 备件选择 -->
    <part-select
      :is-view-part.sync="isViewPart"
      :row-data="rowData"
      :chosen-list.sync="chosenList"
      :cur-select-list.sync="curSelectList"
      @selectiondataPart="selectiondata2"
      :short-list="shortList"
    />
    <!-- 添加附件弹框 -->
    <add-enclosure
    :dialog-form-visible2.sync="dialogFormVisible2"
    @close="close1"
    @updateList="updateList"
    :attachmentUrl="attachmentUrl"
    :attachmentName="attachmentName"
    :popupsState="popupsState"
    />
  </div>
</template>

<script>
import dialogHeader from '@/components/dialogHeader'
import OneTableTemplate from '@/components/templates/oneTable'
// import api from '@/api/vehicleManagement'
import ShortImport from './shortImport'
import AfterSaleImport from './afterSaleImport'
import PartSelect from './partSelectNew'
// import calendarPopups from '@/views/pa/purchasingManagement/partOrderBranchMake/calendarPopups'
import { vehiclePdiPriceInquirys } from '@/api/se/vehiclePdiPriceInquiry'
// import { exportExcel } from '@/utils/getTimeString.js'
import addEnclosure from "./addEnclosure.vue"
import api from '@/api/vehicleManagement'

export default {
  components: {
    // calendarPopups,
    dialogHeader,
    OneTableTemplate,
    ShortImport,
    AfterSaleImport,
    PartSelect,
    addEnclosure,
  },
  props: {
    // 是否关闭弹窗
    isViewPopWindows: {
      type: Boolean,
      default: false
    },
    popupsState: {
      type: String
    },
    // 从网格传入的编辑行数据(json)
    dynamicEditRowData: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    null
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      tableKey: this.$utils.generateId(),
      minOrderAmount: null,
      valid: false,
      chosenList: [],
      curSelectList: [],
      // popUpSwitch: false,
      rowData: {},
      totalType: 0,
      totalAmount: 0,
      totalPurUrgentOrderPriceAmount: 0,
      totalPurUrgentOrderPriceNotTaxAmount: 0,
      totalPurAmountNotTax: 0,
      isViewPart: false,
      isAfterSaleImport: false,
      isViewShortWindows: false,
      dialogFormVisible2:false,//附件信息弹框
      attachmentUrl: '',//附件地址
      attachmentName: '',//附件名称
      shortList: [],//缺件导入禁用
      // apiConfig: vehiclePdiPriceInquirys.queryPartOrderDetails,
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '网点：',
              codeField: 'dlrId',
              textField: 'dlrShortName',
              disabled: true,
              component: () => import('@/views/ve/planReport/components/multipleSearchInput'),
              isMust: true,
              customObj: { showType: 'text' },
              dataToObject: {
                tableComponents: [
                  {
                    compKey: 'compKey1',
                    labelName: '网点编码：',
                    codeField: 'dlrCode',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  },
                  {
                    compKey: 'compKey2',
                    labelName: '网点名称：',
                    codeField: 'dlrShortName',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  }
                ],
                tableCols: [
                  {
                    prop: 'dlrCode',
                    label: '网点编码'
                  },
                  {
                    prop: 'dlrShortName',
                    label: '网点名称'
                  }
                ],
                formField: {
                  dlrShortName: '',
                  dlrCode: ''
                },
                oFields: 'dlrId,dlrShortName',
                returnField: {
                  prop: 'dlrShortName',
                  label: '网点名称'
                },
                api: { APIUrl: 'mp/e3sh/spareparts/finance/bonusOrderMakeService/queryOrgDlrCodes.do', ServiceCode: 'queryOrgDlrCodes' }
              },
              span: 6
            },
            {
              compKey: 'compKey2',
              labelName: '订货日期:',
              codeField: 'purDate',
              component: () =>
                import('@/components/org/datePicker/datePicker'),
              type: 'datePicker',
              isMust: true,
              isRequire: true,
              span: 6
            },
            {
              compKey: 'compKey3',
              labelName: '订单类型：',
              codeField: 'purOrderType',
              textField: 'purOrderTypeCn',
              component: () => import('@/components/org/commonSelect'),
              customObj: {
                api: vehiclePdiPriceInquirys.queryOrderType
              },
              type: 'dropdownList',
              isMul: false,
              isMust: true,
              isRequire: true,
              span: 6
            },
            // {
            //   compKey: 'compKey4',
            //   labelName: '运输方式：',
            //   codeField: 'transportModeId',
            //   textField: 'transportModeName',
            //   component: () => import('@/components/org/commonSelect'),
            //   oFields: 'transportModeId,transportModeName',
            //   customObj: {
            //     api: {
            //       APIUrl: 'mp/e3sh/spareparts/mallorder/partOrderMakeDlrService/queryPartTransports.do'
            //     }
            //   },
            //   type: 'dropdownList',
            //   isMul: false,
            //   isMust: true,
            //   isRequire: true,
            //   span: 6
            // },
            {
              compKey: 'compKey5',
              labelName: '供应商：',
              codeField: 'supplierId',
              textField: 'supplierShortName',
              otherField: 'supplierCode',
              component: () => import('@/views/ve/planReport/components/multipleSearchInput'),
              type: 'inputText',
              isMul: false,
              isMust: true,
              isRequire: true,
              customObj: {
                showType: 'text'
              },
              dataToObject: {
                //
                beforeOpen: comp => {
                  if (!this.$refs['multipleTable'].list.length) {
                    comp.curPopupsVisible = true
                    this.$nextTick(() => {
                      comp.$refs['multipleDialog'].queryTable(1)
                    })
                    return
                  }
                  this.$Modal.confirm({
                    title: '提示',
                    content: '更换供应商后，备件列表将清空，是否更换？',
                    okText: '确定',
                    cancelText: '取消',
                    zIndex: 6000,
                    centered: true,
                    onOk: async() => {
                      this.$refs['multipleTable'].list = []
                      this.totalAmount = 0
                      this.totalType = 0
                      comp.curPopupsVisible = true
                      this.$nextTick(() => {
                        comp.$refs['multipleDialog'].queryTable(1)
                      })
                    },
                    onCancel: async() => {
                      console.log('cancel')
                    }
                  })
                },
                oFields: 'supplierId,supplierShortName',
                tableComponents: [
                  {
                    compKey: 'compKey1',
                    labelName: '供应商编码：',
                    codeField: 'supplierCode',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  },
                  {
                    compKey: 'compKey2',
                    labelName: '供应商名称：',
                    codeField: 'supplierShortName',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  }
                ],
                tableCols: [
                  {
                    prop: 'supplierCode',
                    label: '供应商编码'
                  },
                  {
                    prop: 'supplierShortName',
                    label: '供应商名称'
                  }
                ],
                formField: {
                  supplierCode: '',
                  supplierShortName: ''
                },
                returnField: {
                  prop: 'supplierCode',
                  label: '供应商编码'
                },
                api: {
                  APIUrl: 'mp/e3sh/spareparts/mallorder/partOrderMakeDlrService/querySupplierCode.do'
                }
              },
              span: 6
            },
            {
              compKey: 'compKey6',
              labelName: '订单号:',
              codeField: 'purOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              disabled: true,
              span: 6
            },
            {
              compKey: 'compKey7',
              labelName: '结算方式：',
              codeField: 'billType',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'isBillType,isBillTypeCn',
              isRequire: true,
              options: [1],
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey8',
              labelName: 'VIN码：',
              codeField: 'VIN',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              isShow:true,
              span: 6
            },
            // {
            //   compKey: 'compKey7',
            //   labelName: '是否大客户：',
            //   codeField: 'isExportFlag',
            //   component: () => import('@/components/org/LookupValue'),
            //   oFields: 'statusId,statusText',
            //   options: [
            //     { statusId: '0', statusText: '否' },
            //     { statusId: '1', statusText: '是' }
            //   ],
            //   type: 'dropdownList',
            //   isRequire: true,
            //   isMul: false,
            //   isMust: true
            // }
          ],
      // 标题
      textMap: {
        edit: '备件订单编辑',
        add: '备件订单新增'
      },
      customObj:{
        api: {
          APIUrl:'/mp/e3sh/spareparts/mallorder/partOrderMakeDlrService/queryAfterTechnical.do',
          ServiceCode: 'queryAfterTechnical'
        },
        tableComponents:[
          {
            compKey: 'compKey00',
            labelName: '提交时间:',
            codeField: 'startDate,endDate',
            component: () => import('@/components/org/datePicker/datePicker'),
            dateType: 'daterange',
            isMust: true,
            span: 12
          },
          {
            compKey: 'compKey10',
            labelName: '提交人:',
            codeField: 'submitName',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true,
            span: 12
          },
          {
            compKey: 'compKey30',
            labelName: '批次号:',
            codeField: 'ifBatchNo',
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true,
            span: 12
          }          
        ],
        tableCols: [
          {
            prop: 'ifBatchNo',
            label: '批次号',
            align: 'center',
            width:200
          },
          {
            prop: 'partNo',
            label: '备件编号',
            align: 'center',
            width:200
          },
          {
            prop: 'partName',
            label: '备件名称',
            align: 'center'
          },
          {
            prop: 'purQty',
            label: '备件数量',
            align: 'center'
          },
          {
            prop: 'userName',
            label: '提交用户',
            align: 'center'
          },
          {
            prop: 'submitTime',
            label: '提交时间',
            align: 'center',
            width:150
          }
          
        ],
        formField:{
          startDate: '',
          endDate: '',
          submitName: '',
          ifBatchNo:''
        }
      },
      // 表单数据（无需赋值，由混入对象赋值）
      formField: this.$utils.getFormField(
        this,
        {
          dlrId: '',
          dlrShortName: '', // 网点
          purDate: '', // 订货日期
          purOrderType: '', // 订单类型
          purOrderTypeCn: '', // 订单类型
          // transportModeName: '', // 运输方式
          transportModeId: '', // 运输方式
          supplierCode: '', // 供应商
          supplierShortName: '',
          supplierId: '', // 供应商
          purOrderCode: '', // 订单号
          // isExportFlag: '' // 是否大客户
          billType: '',
          billTypeS: '',
          VIN:'',
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      ),
      // 回调方法对象
      callbackObj: {
        // 网格点击回调事件
        // onRowClick: currentRow => {
        //   this.onRightRowClick(currentRow)
        // },
        // 手动勾选网格时，拿到勾选网格的数据
        // onCheckSelect: (selection, row) => {
        //   this.selectiondata = selection
        // },
        onCheckSelectChange: selection => {
          this.selectiondata = selection

          // this.onCheckSelectChange1(selection)
        }
      },
      selectiondata: [],
      tableButtons: [
        // {
        //   compKey: 'btnKey1',
        //   type: '',
        //   size: 'small',
        //   name: 'chakan',
        //   clickEvent: () => {
        //     this.popUpSwitch = true
        //   },
        //   text: '订货日历',
        //   position: 'left'
        // },
        {
          compKey: 'button10',
          type: '',
          size: 'small',
          name: 'hetongguanli',
          isShow:false,
          clickEvent: () => {
            if (!this.selectiondata.length) return this.$message('请先勾选要计算建议订货量的数据！')
            const loading = this.$loading({ text: `正在计算建议订货量...` })
            this.$requestAPI({
              apiUrl: '/mp/e3sh/spareparts/mallorder/partOrderMakeDlrService/queryMayOrderQty.do',
              variables: {
                list: this.selectiondata
              }
            }).then(res => {
              console.log('计算res',res)
              if (res.result === '1') {
                res.rows.forEach(row => {
                  this.$set(this.$refs['multipleTable'].list, row['index'], row)
                })
              } else {
                this.$message(res.msg ? res.msg : '')
              }
            }).catch(err => {
              if (err.response.data.msg) {
                this.$message(err.response.data.msg)
              } else {
                this.$message(err.message)
              }
            }).finally(() => {
              loading.close()
            })
          },
          text: '建议订货量',
          position: 'left'
        },
        {
          compKey: 'button20',
          type: '',
          size: 'small',
          name: 'inventoryEntry',
          clickEvent: () => {
            this.rowData = {
              supplierId: this.formField.supplierId,
              supplierCode: this.formField.supplierCode
            }
            this.chosenList = this.$refs['multipleTable'].list.map(row => row['partId'])
            const lis = this.$utils.deepCopy(this.$refs['multipleTable'].list)
            lis.forEach(o => o['cur'] = true)
            this.curSelectList = lis
            this.shortList = this.$refs['multipleTable'].list.map(
              (o) => o['partNo']
            )
            this.isAfterSaleImport = true
          },
          text: '售后技术需要',
          position: 'left'
        },
        {
          compKey: 'comKey30',
          type: '',
          size: 'small',
          name: 'importTemplate',
          position: 'upload',
          // clickEvent: () => this.handFileListChange(),
          text: '批量导入'
        },
        {
          compKey: 'button40',
          type: 'text',
          size: 'small',
          name: '',
          position: 'upload',
          text: '模板下载',
          click: event => this.templateDownload()
        },
        { 
          compKey: 'button50', 
          type: 'primary',
          size: 'small',
          class: 'iconfont icon-preservation',
          text: '附件信息',
          isShow: false,
          clickEvent: () => {this.dialogFormVisible2 = true}
        },
        {
          compKey: 'button60',
          type: '',
          size: 'small',
          name: 'preservation',
          clickEvent: () => this.save(),
          text: '保存',
          position: 'right'
        },
        {
          compKey: 'button70',
          type: '',
          size: 'small',
          name: 'realImport',
          clickEvent: () => {
            this.isViewShortWindows = true
            this.shortList = this.$refs['multipleTable'].list.map(
              (o) => o['partNo']
            )
          },
          text: '缺件导入',
          position: 'right'
        },
        {
          compKey: 'button80',
          type: 'primary',
          size: 'small',
          name: 'selecjinpingbeijian',
          clickEvent: () => {
            if (!this.formField.supplierId) {
              return this.$message('请先选择备件供应商!')
            }
            this.rowData = {
              supplierId: this.formField.supplierId,
              supplierCode: this.formField.supplierCode
            }
            this.chosenList = this.$refs['multipleTable'].list.map(row => row['partId'])
            const lis = this.$utils.deepCopy(this.$refs['multipleTable'].list)
            lis.forEach(o => o['cur'] = true)
            this.curSelectList = lis
            this.shortList = this.$refs['multipleTable'].list.map(
              (o) => o['partNo']
            )
            this.isViewPart = true
          },
          text: '备件选择',
          position: 'right'
        },
        {
          compKey: 'button90',
          type: '',
          size: 'small',
          icon: '',
          name: 'quanbushanchu',
          clickEvent: () => this.delete(),
          text: '备件删除',
          position: 'right'
        },

        // {
        //   compKey: 'button',
        //   type: '',
        //   size: 'small',
        //   name: 'reset',
        //   clickEvent: () => {
        //     this.formField.purDate = ''
        //     this.formField.isExportFlag = ''
        //     this.formField.purOrderType = ''
        //     this.formField.transportModeName = ''
        //     this.formField.transportModeId = ''
        //   },
        //   text: '重置',
        //   position: 'right'
        // }

      ],
      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'isCanLack',
              label: '可欠拨',
              width: 50,
              align: 'center',
              isSlot: true
            },
            {
              prop: 'partNo',
              label: '备件号',
              align: 'center'
            },
            {
              prop: 'partName',
              label: '备件名称',
              align: 'center'
            },
            {
              prop: 'unit',
              label: '计量单位',
              align: 'center'
            },
            {
              prop: 'snp',
              label: 'SNP',
              align: 'center'
            },
            {
              prop: 'minPurchasePage',
              label: '最小订货数',
              align: 'center'
            },
            {
              prop: 'purPrice',
              label: '单价',
              align: 'center',
              hidden: false
            },
            {
              prop: 'urgentOrderPrice',
              label: '单价',
              align: 'center',
              hidden: true,
              isSlot:true
            },
            {
              prop: 'purQty',
              label: '订货数量+',
              align: 'center',
              isSlot: true
            },
            {
              // prop: 'oemAccountQty',
              prop: 'sumAccountQty',
              label: '总部库存',
              align: 'center'
            },
            {
              prop: 'mayOrderQty',
              label: '建议订货量',
              align: 'center'
            },
            {
              prop: 'purAmount',
              label: '订货金额',
              align: 'center',
              hidden: false
            },
            {
              prop: 'purUrgentOrderPriceAmount',
              label: '订货金额',
              align: 'center',
              hidden: true
            },
            {
              prop: 'sumAccountQty',
              label: '库存数量',
              align: 'center'
            },
            {
              prop: 'sumAbleUseQty',
              label: '可用库存',
              align: 'center'
            },
            {
              prop: 'validLackQty',
              label: '有效欠拨数量',
              align: 'center'
            }
          ]
    }
  },
  mounted() {
    this.getMinOrderAmount()
    // if (this.popupsState === 'add') {
    const { DLR_ID, DLR_NAME, DLR_CODE } = this.$store.state.user.orgInfo
    this.formField.dlrId = DLR_ID
    this.formField.dlrShortName = DLR_NAME
    this.loadDatas()
    // this.getTransForm()
    // }
  },
  watch: {
    'formField.billType': {
      handler(val) {
        if (val) {
          if (val === '0') {
            this.formField.billTypeS = '1'
          } else {
            this.formField.billTypeS = '2'
          }
        } else {
          this.formField.billTypeS = ''
        }
      },
    },
    'formField.purOrderType': {
      handler(type) {
        this.showPriceByOrderType(type)
      },
      immediate: true
    },
    // 订单类型
    'formField.purOrderTypeCn':{
      handler(oldval){
        if(oldval==='特殊订单'){
          this.tableComponents[6].isShow = true
          this.tableButtons[4].isShow = true
        } else {
          this.tableComponents[6].isShow = false
          this.tableButtons[4].isShow = false
          this.formField.VIN=""
          this.attachmentName=""
          this.attachmentUrl=""
        }
     },
     immediate: true,
    },
    '$refs.multipleTable.list': {
      handler(val){
        console.log("val:",val)
      },
      immediate:true
    },
    // 订单类型改变，将purOrderTypeCn的后两位添插入订单号中
    'formField.purOrderType': {
      handler(val){
        let orderType=val.slice(-2)
        let oldCode=this.formField.purOrderCode.split("")
        oldCode.splice(2,2,orderType)
        this.formField.purOrderCode = oldCode.join("")
      }
    }
  },
  methods: {
    // 获取当前年月日
    addDate() {
      const nowDate = new Date()
      const date = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        date: nowDate.getDate()
      }
      const newmonth = date.month > 10 ? date.month : '0' + date.month
      const day = date.date > 10 ? date.date : '0' + date.date
      this.formField.purDate = date.year + '-' + newmonth + '-' + day
    },
    // 接收子组件传来的附件名称和地址
    updateList(val){
      this.attachmentUrl = val.url
      this.attachmentName = val.name
    },
    showPriceByOrderType(type) {
      if (type === 'A002') {
        // 选择了紧急订单
        this.tableCols.find(col => col.prop === 'purPrice').hidden = true
        this.tableCols.find(col => col.prop === 'urgentOrderPrice').hidden = false
        this.tableCols.find(col => col.prop === 'purAmount').hidden = true
        this.tableCols.find(col => col.prop === 'purUrgentOrderPriceAmount').hidden = false
      } else {
        this.tableCols.find(col => col.prop === 'purPrice').hidden = false
        this.tableCols.find(col => col.prop === 'urgentOrderPrice').hidden = true
        this.tableCols.find(col => col.prop === 'purAmount').hidden = false
        this.tableCols.find(col => col.prop === 'purUrgentOrderPriceAmount').hidden = true
      }
      this.tableKey = 'tableKey' + this.$utils.generateId()
      this.calcTotals()
    },
    async getMinOrderAmount() {
      let response
      const apiUrl = '/mp/e3sh/spareparts/TariffAdjustService/getMinOrderAmount.do'
      try { response = await this.$requestAPI({ apiUrl, method: 'GET' }) } catch (e) { return false }
      if (response.result !== '1') { return this.$message(response.msg || '起订金额获取失败!') }
      this.minOrderAmount = response.rows[0].ATTRIBUTE1
    },
    // 售后技术需求
    addData(datas) {
      datas.forEach(row => {
        this.$set(row, 'isCanLack', '1')
        this.$set(row, 'purAmount', (Number(row['purQty']) * Number(row['purPrice'])).toFixed(2))
      })
      this.$refs['multipleTable'].list.push(...datas)
      // purAmount = purQty * purPrice
      this.totalType = this.$refs['multipleTable'].list.length
      this.totalAmount = this.$refs['multipleTable'].list.reduce((amount, row) => {
        return Number(amount) + (Number(row['purAmount']) || 0)
      }, 0).toFixed(2)
    },
    // 默认 运输方式为公路
    async getTransForm() {
      let res
      try {
        res = await this.$requestAPI({
          apiUrl: 'mp/e3sh/spareparts/mallorder/partOrderMakeDlrService/queryPartTransports.do',
          variables: {}
        })
      } catch (e) { return }
      if (res.result !== '1') { return }
      const target = res.rows.find(row => row['transportModeName'] === '公路')
      this.formField['transportModeId'] = target.transportModeId
    },
    /**
     * @description 关闭弹窗
     * @time 2021、01、22
     */

    // 计算
    numChange(val, row, col, index) {
      const errorReset = msg => {
        row[col['prop']] = ''
        row['purAmount'] = '0.00'
        val ? this.$alert(msg, '提示') : ''
      }
      const panter = /c|(^[1-9][0-9]*$)/
      if (!panter.test(val)) {
        errorReset('请输入正确的订货数量!')
      } else if (Number(val) < Number(row['minPurchasePage'])) {
        errorReset('[ 订货数量 ] 不能小于 [ 最小订货量 ]！')
      } else if (Number(val) % Number(row['snp'])) {
        errorReset('[ 订货数量 ] 只能为 [ snp ]的倍数!')
      } else {
        this.$set(row, 'purAmount', (Number(val) * Number(row['purPrice'])).toFixed(2))
        this.calcOtherPrice(row)
      }
      // purAmount = purQty * purPrice
      this.totalType = this.$refs['multipleTable'].list.length
      this.calcTotals()
    },
    resetForm() {
      this.formField.dlrId = ''
      this.formField.dlrShortName = ''
      this.formField.purDate = ''
      this.formField.purOrderType = ''
      this.formField.transportModeName = ''
      this.formField.supplierId = ''
      this.formField.supplierShortName = ''
      this.formField.purOrderCode = ''
      this.formField.isExportFlag = ''
      this.dynamicEditRowData.updateControlId = ''
      this.dynamicEditRowData.purchaseOrderId = ''
      // this.tableComponents[0].options = []
      this.formField.billType = ''
      this.formField.VIN = ''
    },
    resetTotals() {
      this.totalAmount = 0.00
      this.totalType = 0
    },
    resetIconv() {
      this.$nextTick(() => {
        for (const attr in this.$refs['multipleTable'].$refs) {
          if (attr.startsWith('true')) {
            this.$refs['multipleTable'].$refs[attr][0].$children[0].$children[2].iconV = ''
          }
        }
      })
    },
    close() {
      this.resetTotals()
      this.resetForm()
      this.resetIconv()
      this.$refs.multipleTable.list = []
      this.attachmentName=""
      this.attachmentUrl=""
      // this.$emit('update:isViewPopWindows',false)
      this.formField.purOrderTypeCn = ''
      this.$emit('update:is-view-pop-windows', false)
    },
    closeShort() {
      this.isViewShortWindows = false
    },
    closeSale() {
      this.isAfterSaleImport = false
    },
    // closePart() {
    //   this.isViewPart = false
    // },
    // 关闭附件信息
    close1(){
      this.dialogFormVisible2 = false
    },
    addIndex(rows) {
      rows.forEach((row, idx) => { row['index'] = idx })
      return rows
    },
    async loadBillType() {
      let response
      const apiUrl = '/mp/e3sh/spareparts/mallorder/partOrderMakeDlrService/findDlrBillType.do'
      const variables = {}
      try { response = await this.$requestAPI({ apiUrl, variables }) } catch (e) { return false }
      if (response.result !== '1') { return this.$message(response.msg || '结算方式加载失败!') }
      this.$nextTick(() => {
        this.tableComponents.find(comp => comp.codeField === 'billType').options = response.rows
      })
    },
    async open() {
      if(this.popupsState === 'add'){
        this.addDate()//获取订货日期为当天日期
      }
      this.dialogFormVisible2 = false
      // 加载 结算方式
      await this.loadBillType()
      if (this.popupsState == 'edit') {
        const { purchaseOrderId, updateControlId, supplierCode, supplierId, supplierShortName } = this.dynamicEditRowData
        const queryObj = {
          // 保存mutation
          type: 'mutation',
          // api配置
          apiConfig: vehiclePdiPriceInquirys.queryPartOrderDetails,
          // 条件/实体参数（变量），根据typeParam中的定义配置
          variables: { purchaseOrderId, updateControlId, supplierId, supplierCode, supplierShortName }
        }
        // 转换了中台请求格式数据
        var paramD = this.$getParams(queryObj)
        // 调用中台API方法（可复用）
        this.$requestAPI(paramD).then(response => {
          let billType = response.rows[0].partOrder[0].billType
          if (billType === '1') {
            billType = '0'
          } else if (billType === '2') {
            billType = '1'
          }
          this.$refs.multipleTable.list = this.addIndex(response.rows[0].partOrderDetails)
          this.calcTotals()
          this.formField.billType = billType
          this.formField.purOrderCode =
            response.rows[0].partOrder[0].purOrderCode
          this.formField.dlrId = response.rows[0].partOrder[0].dlrId
          this.formField.dlrShortName = response.rows[0].partOrder[0].dlrShortName
          this.formField.purDate = response.rows[0].partOrder[0].purDate
          this.formField.purOrderType = response.rows[0].partOrder[0].purOrderType
          // this.formField.transportModeId =
          //   response.rows[0].partOrder[0].transportModeId
          this.formField.supplierId = response.rows[0].partOrder[0].supplierId
          this.formField.supplierShortName = response.rows[0].partOrder[0].supplierShortName
          this.formField.isExportFlag =
            response.rows[0].partOrder[0].isExportFlag
          this.totalAmount = response.rows[0].partOrder[0].purAmount
          this.totalType = response.rows[0].partOrder[0].orderVariety
          this.formField.VIN = response.rows[0].partOrder[0].VIN
          this.formField.purOrderTypeCn = response.rows[0].partOrder[0].purOrderTypeCn
          this.attachmentName = response.rows[0].partOrder[0].attachmentName
          this.attachmentUrl = response.rows[0].partOrder[0].attachmentUrl
        })
      } else {
        this.attachmentName=""
        this.attachmentUrl=""
        this.tableComponents[6].isShow = false
        this.tableButtons[4].isShow = false
        // 从vuex 获取网点数据
        const { DLR_ID, DLR_NAME, DLR_CODE } = this.$store.state.user.orgInfo
        this.formField.dlrId = DLR_ID
        this.formField.dlrShortName = DLR_NAME
        this.$nextTick(() => {
          this.loadDatas()
        })
      }
    },
    loadDatas() {
      // 获取订单号
      const queryObj1 = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: vehiclePdiPriceInquirys.queryPartOrderCode,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {}
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj1)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then(response => {
        const { purOrderCode, supplierCode, supplierId, supplierShortName } = response.rows[0]
        this.formField.purOrderCode = purOrderCode
        this.formField.supplierCode = supplierCode
        this.formField.supplierId = supplierId
        this.formField.supplierShortName = supplierShortName
        // this.$refs['multipleTable'].pageTotal = response.records
      })
    },

    // 备件删除
    delete() {
      if (!this.selectiondata.length) return this.$message('请选择要删除的数据！')
      // 需要删除数据的 index 列表
      this.$refs['multipleTable'].list = this.$refs['multipleTable'].list.reduce((newList, row, idx) => {
        if (!this.selectiondata.map(o => o['partId']).includes(row['partId'])) {
          newList.push(row)
        }
        return newList
      }, [])
      // 重新加索引
      this.$refs['multipleTable'].list.forEach((row, index) => {
        row['index'] = index
      })
      // purAmount = purQty * purPrice 更新价格和种类
      this.totalType = this.$refs['multipleTable'].list.length
      this.calcTotals()
      // this.totalAmount = this.$refs['multipleTable'].list.reduce((amount, row) => {
      //   return amount + Number(row['purAmount'])
      // }, 0)
      this.selectiondata = []
    },
    // 保存
    save() {
      this.$utils.validataMoth(this, 'validpage')
      if (!this.$refs['multipleTable'].list.length) return this.$message('请选择备件!')
      let qtyisNull = false
      this.$refs['multipleTable'].list.every((row) => {
        if (!row['purQty']) {
          qtyisNull = true
          return false
        }
        return true
      })
      if (qtyisNull) {
        return this.$message('网格中[ 订货数量+ ]为必填项!')
      }
      // 订单类型为特殊订单时   VIN与附件信息为必填
      // if(this.formField.purOrderTypeCn==='特殊订单'){
      //   if(this.attachmentUrl===''|| this.attachmentName ===''){
      //     let num = true
      //     if(this.attachmentUrl===''|| this.attachmentName ===''){
      //       this.$message({
      //       message: "请上传附件",
      //       type: "warning",
      //      });
      //      num = false
      //     }
      //     return num
      //   }
      // }

      const { purOrderTypeCn } = this.formField
      if (purOrderTypeCn && purOrderTypeCn === '常规订单') {
        if (!this.totalAmount || Number(this.totalAmount) < Number(this.minOrderAmount)) {
          return this.$alert(`总金额不能小于起订额度 ￥${this.minOrderAmount}！`, '提示')
        }
      }
      
      if (this.valid) {
        var purchaseOrderId = this.dynamicEditRowData.purchaseOrderId
        var purOrderCode = this.formField.purOrderCode
        this.$refs.multipleTable.list.forEach(item => {
          item.purchaseOrderId = purchaseOrderId
          item.purOrderCode = purOrderCode
        })
        const queryObj = {
          // 保存mutation
          type: 'mutation',
          // api配置
          apiConfig: vehiclePdiPriceInquirys.updatePartOrderMake,
          // 条件/实体参数（变量），根据typeParam中的定义配置
          variables: {
            dlrId: this.formField.dlrId,
            purDate: this.formField.purDate.slice(0,10),
            billType: this.formField.billTypeS,
            purOrderType: this.formField.purOrderType,
            // transportModeId: this.formField.transportModeId,
            supplierId: this.formField.supplierId,
            supplierCode: this.formField.supplierCode,
            supplierShortName: this.formField.supplierShortName,
            purOrderCode: this.formField.purOrderCode,
            isExportFlag: this.formField.isExportFlag,
            purchaseOrderId: this.dynamicEditRowData.purchaseOrderId,
            updateControlId: this.dynamicEditRowData.updateControlId,
            orderVariety: this.totalType,
            purAmount: this.totalAmount,
            purUrgentOrderPriceAmount: this.totalPurUrgentOrderPriceAmount,
            purUrgentOrderPriceNotTaxAmount: this.totalPurUrgentOrderPriceNotTaxAmount,
            purAmountNotTax: this.totalPurAmountNotTax,
            list: this.$refs.multipleTable.list,
            VIN:this.formField.VIN,
            attachmentName:this.attachmentName,//附件名称
            attachmentUrl:this.attachmentUrl,//附件地址
          }
        }
        // 转换了中台请求格式数据
        var paramD = this.$getParams(queryObj)
        // 调用中台API方法（可复用）
        this.$requestAPI(paramD).then(response => {
          if (response.result === '1') {
            this.$message(response.msg || '保存成功！')
            // this.isViewPopWindows = false
            this.$emit('isViewPopWindows',false)
            this.$emit('close')
          } else {
            // 保存失败
            this.$message(response.msg || '保存失败！')
          }
        })
      }
    },
    // 缺件导入
    selectiondata1(selectiondata) {
      console.log(selectiondata)
      selectiondata.forEach(item => {

        this.$refs.multipleTable.list.push(item)
      })
    },
    calcOtherPrice(row) {
      // 数量
      const purQty = Number(row['purQty'])
      //单价
      const purPrice = Number(row['purPrice'])
      // 浮动价（含税）
      const urgentOrderPrice = Number(row['urgentOrderPrice'])
      // 浮动价 （不含税）
      const urgentOrderPriceNotTax = Number(row['urgentOrderPriceNotTax'])
      // 正常订单价不含税
      const purPriceNotTax = Number(row['purPriceNotTax'])
      // 计算 总浮动价 （含税） urgentOrderPrice * purQty
      // const purUrgentOrderPriceAmount = urgentOrderPrice * purQty
      let purUrgentOrderPriceAmount = urgentOrderPrice ==  0 ? purPrice * purQty : urgentOrderPrice * purQty
      // 计算 总浮动价 （不含税）urgentOrderPriceNotTax * purQty
      const purUrgentOrderPriceNotTaxAmount = urgentOrderPriceNotTax * purQty
      // 计算 总正常订单价 （不含税） purPriceNotTax * purQty
      const purAmountNotTax = purPriceNotTax * purQty
      // 赋值
      row['purUrgentOrderPriceAmount'] = purUrgentOrderPriceAmount.toFixed(2)
      row['purUrgentOrderPriceNotTaxAmount'] = purUrgentOrderPriceNotTaxAmount.toFixed(2)
      row['purAmountNotTax'] = purAmountNotTax.toFixed(2)
    },
    calcTotals() {
      const {
        totalAmount,
        totalPurUrgentOrderPriceAmount,
        totalPurUrgentOrderPriceNotTaxAmount,
        totalPurAmountNotTax
      } = this.$refs['multipleTable'].list.reduce((amount, row) => {
        const totalAmount = amount['totalAmount']
        const totalPurUrgentOrderPriceAmount = amount['totalPurUrgentOrderPriceAmount']
        const totalPurUrgentOrderPriceNotTaxAmount = amount['totalPurUrgentOrderPriceNotTaxAmount']
        const totalPurAmountNotTax = amount['totalPurAmountNotTax']
        amount['totalAmount'] = totalAmount + (Number(row['purAmount']) || 0)
        amount['totalPurUrgentOrderPriceAmount'] = totalPurUrgentOrderPriceAmount + (Number(row['purUrgentOrderPriceAmount']) || 0)
        amount['totalPurUrgentOrderPriceNotTaxAmount'] = totalPurUrgentOrderPriceNotTaxAmount + (Number(row['purUrgentOrderPriceNotTaxAmount']) || 0)
        amount['totalPurAmountNotTax'] = totalPurAmountNotTax + (Number(row['purAmountNotTax']) || 0)
        return amount
      }, {
        totalAmount: 0,
        totalPurUrgentOrderPriceAmount: 0,
        totalPurUrgentOrderPriceNotTaxAmount: 0,
        totalPurAmountNotTax: 0
      })
      this.totalAmount = totalAmount.toFixed(2)
      this.totalPurUrgentOrderPriceAmount = totalPurUrgentOrderPriceAmount.toFixed(2)
      this.totalPurUrgentOrderPriceNotTaxAmount = totalPurUrgentOrderPriceNotTaxAmount.toFixed(2)
      this.totalPurAmountNotTax = totalPurAmountNotTax.toFixed(2)
    },
    // 备件选择
    selectiondata2(selectiondata) {
      selectiondata.forEach(row => {
        row['urgentOrderPrice'] = Number(row['urgentOrderPrice']).toFixed(2)
        // 设置默认可欠拨
        if (!('isCanLack' in row)) { this.$set(row, 'isCanLack', '1') }
        // 设置默认订货数量
        // if (!row['cur']) { row['purQty'] = row['minPurchasePage'] }
        this.calcOtherPrice(row)
      })
      this.$refs['multipleTable'].list = selectiondata
      this.$nextTick(() => {
        this.totalType = this.$refs['multipleTable'].list.length
        this.$refs['multipleTable'].list.forEach(row => {
          this.$set(row, 'purAmount', (Number(row['purQty']) * Number(row['purPrice'])).toFixed(2))
        })
        this.calcTotals()
      })
    },
    // 批量导入模板下载
    templateDownload() {
      const fileName = this.$utils.fileNameWithTime('备件订单制作_网点.xlsx')
      this.$requestAPI({
        apiUrl:
          '/mp/e3sh/spareparts/mallorder/partOrderMakeDlrService/getPartOrderExcelTemplate.do',
        variables: { dataType: 'excel' }
      })
        .then(res => {
          this.$utils.downloadFile(res, fileName)
        })
        .catch(err => {
          console.log(err)
        })
    },
    handFileListChange(file, fileList) {
      if (this.beforeAvatarUpload(file)) {
        this.handleChange(file)
      }
    },
    beforeAvatarUpload(file) {
      if (file.size > 50 * 1024 * 1024) {
        this.$message({
          message: '文件大小不能超过50M',
          type: 'warning'
        })
        return false
      }
      const fileType = file.name.substr(file.name.lastIndexOf('.') + 1)
      if (fileType != 'xls' && fileType != 'xlsx') {
        this.$message({
          message: '只能导入后缀为xls,xlsx的文件！',
          type: 'warning'
        })
        return false
      }
      return true
    },
    handleChange(param) {
      // console.log(param)
      // return
      const loading = this.$loading({
        lock: true,
        text: '导入中...',
        background: 'rgba(0, 0, 0, 0.5)'
      })
      const that = this
      const url =
        '/mp/e3sh/spareparts/mallorder/partOrderMakeDlrService/importPartOrderExcel.do'
      that
        .$requestUpload(url, param, {
          code: this.formField.supplierCode
        })
        .then(response => {
          if (response.result === '1') {
            if(!this.$refs.multipleTable.list.length){
              this.$refs.multipleTable.list = response.rows
            } else {
              const partIds = this.$refs.multipleTable.list.map(row => row['partId'])
              response.rows.forEach((element, index) => {
                if (!partIds.includes(element['partId'])) {
                  // 若数据不存在 则加入网格
                  this.$refs.multipleTable.list.push(element)
                } else {
                  // 数据存在,替换
                  this.$refs['multipleTable'].list[
                    this.$refs['multipleTable'].list.findIndex(o => o['partId'] === element['partId'])
                  ] = element
                }
              })
            }            
            // 加索引
            this.$refs['multipleTable'].list.forEach((row, index) => {
              row['index'] = index              
              let sum = Number((Number(row.purPrice) * Number(row.purQty)).toFixed(2))
              that.$set(row,'purAmount',sum)
              that.totalAmount += sum
            })
            let queryLength = this.$refs['multipleTable'].list.length
            that.totalType = queryLength == undefined || null ? 0 : queryLength
            this.$message({
              message: '导入成功',
              type: 'success'
            })
          } else {
            this.$message({
              message: response.msg,
              type: 'warning'
            })
          }
        })
        .catch(err => {})
        .finally(() => {
          loading.close()
        })
    }
  }
}
</script>
<style lang="scss" scoped>
  /deep/ .el-table {
    transition: .5s;
  }
</style>
